<template>
  <div>
    <a-modal
      :title="isEdit ? '编辑' : '新增'"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :width="600"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model
        ref="ruleForm"
        :model="formData"
        :rules="rules"
        layout="horizontal"
        labelAlign="left"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-form-model-item label="角色名称" prop="role_name">
          <a-input v-model="formData.role_name" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item label="备注">
          <a-textarea v-model="formData.remark" :auto-size="{ minRows: 2, maxRows: 5 }" placeholder="请输入" />
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>
  <script>
import { editRoleApi, getRoleDetailApi } from '@/api/manager'
export default {
  data() {
    return {
      isEdit: false,
      visible: false,
      confirmLoading: false,
      pkey: null,
      formData: {
        role_name: '', // 角色名称
        remark: '',
        authority: [], // 权限分配
      },
      rules: {
        role_name: [{ required: true, message: '请输入角色名称', trigger: 'change' }],
        authority: [{ required: true, message: '请分配权限', trigger: 'change' }],
      },
    }
  },
  methods: {
    add() {
      this.isEdit = false
      this.visible = true
      this.resetForm()
    },
    edit(row) {
      this.isEdit = true
      this.visible = true
      this.pkey = row.pkey
      this.getRoleDetail()
    },
    resetForm() {
      this.pkey = null
      this.formData.role_name = ''
      this.formData.remark = ''
    },
    handleOk() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.confirmLoading = true
          let formObj = { ...this.formData }
          if (this.isEdit) {
            formObj.pkey = this.pkey
          }
          const { statusCode, errors } = await editRoleApi(formObj)
          this.confirmLoading = false
          if (statusCode == 200) {
            this.visible = false
            this.$message.success('保存成功！')
            this.resetForm()
            this.$parent.getTableData()
          } else {
            this.$message.error(errors)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
    // 获取角色名称
    async getRoleDetail() {
      const { data } = await getRoleDetailApi({
        pkey: this.pkey
      })
      this.formData.role_name = data.role_name
      this.formData.remark = data.remark
    }
  },
}
</script>
      
<style lang="less" scoped>
.three {
  max-height: 400px;
  overflow-y: auto;
}
</style>